package com.example.music.controller;

import com.example.music.entity.Ranks;
import com.example.music.service.RankService;
import com.example.music.utils.AjaxJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("rank")
public class RankController {
    @Autowired
    RankService rankService;

    @PostMapping("add")
    public AjaxJson add(@RequestBody Ranks ranks){
        List<Ranks> ranks1 = rankService.selectAll();
        boolean b = ranks1.parallelStream().anyMatch(e -> (
                (e.getConsumerId().equals(ranks.getConsumerId()) &&
                        e.getSongListId().equals(ranks.getSongListId()))
        ));
        if (b){
            return AjaxJson.getError();
        }else {
            Integer add = rankService.add(ranks);
            if (add != 0){
                return AjaxJson.getSuccess(add.toString());
            }else {
                return AjaxJson.getError(add.toString());
            }
        }
    }

    @PostMapping("rank")
    public AjaxJson rank(@RequestParam String songListId){
        List<Ranks> song_list_id = rankService.selectItemsByParam("song_list_id", songListId);
        int all = song_list_id.stream().mapToInt(Ranks::getScore).sum();
        int avg = 0;
        if (song_list_id.size() != 0){
            avg = all/song_list_id.size();
        }
        return AjaxJson.getSuccess(String.valueOf(avg));
    }
}
